import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

interface NumberHistory {
  value: number
  timestamp: number
  type: 'update' | 'submit'
}

export const useHistoryStore = defineStore('history', () => {
  const history = ref<NumberHistory[]>([])
  const maxHistory = 10

  // 添加计算属性
  const lastOperation = computed(() => history.value[0])
  const totalOperations = computed(() => history.value.length)
  const updateCount = computed(() => 
    history.value.filter(h => h.type === 'update').length
  )
  const submitCount = computed(() => 
    history.value.filter(h => h.type === 'submit').length
  )

  const addHistory = (value: number, type: NumberHistory['type']) => {
    history.value.unshift({
      value,
      timestamp: Date.now(),
      type
    })

    if (history.value.length > maxHistory) {
      history.value.pop()
    }

    // 保存到本地存储
    saveToLocalStorage()
  }

  const clearHistory = () => {
    history.value = []
    localStorage.removeItem('number-history')
  }

  // 本地存储相关
  const saveToLocalStorage = () => {
    localStorage.setItem('number-history', JSON.stringify(history.value))
  }

  const loadFromLocalStorage = () => {
    const saved = localStorage.getItem('number-history')
    if (saved) {
      try {
        history.value = JSON.parse(saved)
      } catch (e) {
        console.error('Failed to load history:', e)
        clearHistory()
      }
    }
  }

  // 初始化时加载历史记录
  loadFromLocalStorage()

  return {
    history,
    lastOperation,
    totalOperations,
    updateCount,
    submitCount,
    addHistory,
    clearHistory
  }
}) 